package com.data.app.commons.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;

/**
 * @author Dbj
 * @date 2022年04月25日  14:41
 */
public class PinyinUtils {
    /**
     *判断是否是中文
     */
    private static final String MATCH = "[\\u4e00-\\u9fa5]";

    public static String getPinyin(String chinese){
        HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();
        formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        formart.setVCharType(HanyuPinyinVCharType.WITH_V);
        return getResultByChinese(chinese,formart);
    }

    /**
     * @desc  将中文转换成拼音，转换失败返回空字符串
     */
    private static String getResultByChinese(final String chinese,HanyuPinyinOutputFormat formart){
        char[] arrays = chinese.trim().toCharArray();
        StringBuilder result = new StringBuilder();
        try {
            for (int i=0;i<arrays.length;i++) {
                char ti = arrays[i];
                //匹配是否是中文
                if(Character.toString(ti).matches(MATCH)){
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti,formart);
                    result.append( temp[0]);
                }else{
                    result.append( ti);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
            return "";
        }
        return result.toString();
    }
    /**
     * 获取各省表的后缀
     */
    public static  String buildProvinceSubfix(String province) {
        String pinyinOfProvince = "";
        if(StringUtils.isNotBlank(province)){
            pinyinOfProvince = PinyinUtils.getPinyin(province);
            if("山西省".equals(province)){
                pinyinOfProvince = (pinyinOfProvince+"1");
            }
            pinyinOfProvince = ("_"+pinyinOfProvince);
        }
        return pinyinOfProvince;
    }

  public static void main(String[] args) {
        System.out.println(getPinyin("山东省"));
  }
}
